package cn.wildfirechat.app.second.service.impl;

import cn.wildfirechat.app.RestResult;
import cn.wildfirechat.app.jpa.*;
import cn.wildfirechat.app.model.UserMemberInfoResponse;
import cn.wildfirechat.app.pojo.PointsConingResponse;
import cn.wildfirechat.app.pojo.RewardPointsRequest;
import cn.wildfirechat.app.second.service.ZlService;
import cn.wildfirechat.common.ErrorCode;
import cn.wildfirechat.pojos.InputOutputUserInfo;
import cn.wildfirechat.sdk.UserAdmin;
import cn.wildfirechat.sdk.model.IMResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class ZlServiceImpl implements ZlService {
    @Autowired
    private UserPointsRepository userPointsRepository;
    @Autowired
    private PointsConfigDetailRepository pointsConfigDetailRepository;
    @Autowired
    private PointsConfigRepository pointsConfigRepository;
    @Autowired
    private UserPointsLogRepository userPointsLogRepository;
    @Autowired
    private PostsRepository postsRepository;
    @Autowired
    private PCLoginRepository pcLoginRepository;
    @Autowired
    private FriendRepository friendRepository;
    @Autowired
    private GroupAssistantRepository groupAssistantRepository;
    @Autowired
    private LuckyNumberRepository luckyNumberRepository;

    @Autowired
    private TransactionTemplate transactionTemplate;


    @Override
    public RestResult getUserPoints(String userId) {
        return RestResult.ok(userPointsRepository.findByUid(userId));

    }

    @Override
    public RestResult getUserPointsLog(String userId) {
        return RestResult.ok(userPointsLogRepository.findByUid(userId));
    }

    @Override
    public RestResult getPointsConing() {
        // 查询配置信息
        Iterable<PointsConfig> all = pointsConfigRepository.findAll();
        List<PointsConingResponse> responses = new ArrayList<>();
        for (PointsConfig pointsConfig : all) {
            PointsConingResponse pointsConingResponse = new PointsConingResponse();
            pointsConingResponse.setConfig(pointsConfig);
            pointsConingResponse.setDetails(pointsConfigDetailRepository.findByConfigId(pointsConfig.getId()));
            responses.add(pointsConingResponse);
        }
        return RestResult.ok(responses);
    }

    @Override
    public RestResult rewardPoints(String userId, RewardPointsRequest request) {
        // 校验用户积分是否足够
        int count = userPointsRepository.findByUidAndPoints(userId,request.getPoints());
        if (count == 0){
            return RestResult.error(RestResult.RestCode.ERROR_JF_NOT);
        }
        // 查询动态信息
        Optional<Posts> posts = postsRepository.findById(request.getPostsId());
        if (!posts.isPresent()){
            return RestResult.error(RestResult.RestCode.ERROR_INFO_NOT_EXIST);
        }
        Posts p = posts.get();
        // 生成积分记录
        // 被打赏人记录
        UserPointsLog userPointsLog = new UserPointsLog();
        // 打赏人记录
        UserPointsLog DonorPointsLog = new UserPointsLog();
        try {
            IMResult<InputOutputUserInfo> getUserResult = UserAdmin.getUserByUserId(p.getUserId());
            // 打赏人
            IMResult<InputOutputUserInfo> getDonorResult = UserAdmin.getUserByUserId(userId);
            if (getDonorResult == null || getDonorResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS){
                return RestResult.error(RestResult.RestCode.ERROR_INFO_NOT_EXIST);
//                return "打赏用户不存在";
            }
            if(getUserResult == null || getUserResult.getErrorCode() != ErrorCode.ERROR_CODE_SUCCESS) {
                return RestResult.error(RestResult.RestCode.ERROR_INFO_NOT_EXIST);
//                return "用户不存在";
            }
            // 被打赏人
            InputOutputUserInfo result = getUserResult.getResult();
            userPointsLog.setMobile(result.getMobile());
            userPointsLog.setUserName(result.getDisplayName());
            userPointsLog.setUid(p.getUserId());

            InputOutputUserInfo donorResult = getDonorResult.getResult();
            DonorPointsLog.setMobile(donorResult.getMobile());
            DonorPointsLog.setUserName(donorResult.getDisplayName());
            DonorPointsLog.setUid(userId);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        userPointsLog.setPoints(request.getPoints());
        userPointsLog.setDonorUid(userId);
        userPointsLog.setOperateType(1);
        userPointsLog.setSourceType(2);
        userPointsLog.setDynamicId(p.getId().toString());

        DonorPointsLog.setPoints(request.getPoints());
        userPointsLog.setDonorUid(p.getUserId());
        DonorPointsLog.setOperateType(2);
        DonorPointsLog.setSourceType(2);
        DonorPointsLog.setDynamicId(p.getId().toString());
        // 查询被打赏人积分信息
        UserPoints userPoints = userPointsRepository.findByUid(p.getUserId());
        transactionTemplate.execute(e->{
            userPointsLogRepository.save(userPointsLog);
            userPointsLogRepository.save(DonorPointsLog);
            // 扣除用户积分
            int subUserPoints = userPointsRepository.updateSubUserPoints(userId, request.getPoints());
            // 增加动态发布者积分
            if (userPoints == null){
                UserPoints newUserPoints = new UserPoints();
                newUserPoints.setUid(p.getUserId());
                newUserPoints.setUserName(userPointsLog.getUserName());
                newUserPoints.setMobile(userPointsLog.getMobile());
                newUserPoints.setAvailablePoints(request.getPoints());
                newUserPoints.setTotalPoints(request.getPoints());
                userPointsRepository.save(newUserPoints);
            }else {
                userPointsRepository.updateAddUserPoints(p.getUserId(),-request.getPoints());
            }
            return RestResult.ok(subUserPoints > 0);
        });
        return RestResult.ok();
    }

    @Override
    public RestResult getUserMemberInfo(String userId) {
        UserMemberInfoResponse response = new UserMemberInfoResponse();
        // 加好友 uid
        Friend friend = friendRepository.findByOwnerId(userId, LocalDateTime.now());
       // PC端 uid
        PCLogin pcLogin = pcLoginRepository.findByOwnerId(userId,LocalDateTime.now());
        // 靓号 uid
        int count = luckyNumberRepository.countByUserId(userId);

        if (friend != null){
            response.setFriendPermission(true);
        }
        if (pcLogin != null){
            response.setPcPermission(true);
        }
        if (count > 0){
            response.setLuckyNumberPermission(true);
        }
        return RestResult.ok(response);
    }
}
